package controllers

import (
	"supershare/backend/models"
	"time"

	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/server/web"
)

// StatisticsController 统计控制器
type StatisticsController struct {
	web.Controller
}

// GetOverview 获取系统概览统计数据
func (c *StatisticsController) GetOverview() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 获取会员数量
	userCount, _ := models.GetMemberCount(permResult.Admin.FranchiseId)

	// 获取订单数据
	orderStats, _ := models.GetOrderStatistics(permResult.Admin.FranchiseId)

	// 获取场地数量
	venueCount, _ := models.GetVenueCount(permResult.Admin.FranchiseId)

	// 获取门店数量
	bookingCount, _ := models.GetStoreCount(permResult.Admin.FranchiseId)

	// 获取优惠券发放数量
	couponIssueCount, _ := models.GetCouponIssueCount(permResult.Admin.FranchiseId)

	// 计算总收入（以分为单位）
	totalRevenue := orderStats.TotalAmount

	// 获取订单趋势数据
	orderTrend, _ := getOrderTrend(30, permResult.Admin.FranchiseId)

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"userCount":    userCount,
			"orderCount":   orderStats.TotalOrders,
			"venueCount":   venueCount,
			"bookingCount": bookingCount,
			"totalRevenue": totalRevenue,
			"couponCount":  couponIssueCount,
			// 添加额外的统计数据
			"todayOrders":   orderStats.TodayOrders,
			"todayAmount":   orderStats.TodayAmount,
			"pendingOrders": orderStats.PendingOrders,
			"orderTrend":    orderTrend,
		},
	}
	c.ServeJSON()
}

// TrendData 趋势图数据结构
type TrendData struct {
	Date  string `json:"date"`
	Type  string `json:"type"`
	Value int64  `json:"value"`
}

// 获取订单趋势数据
func getOrderTrend(days int, franchiseId int64) ([]TrendData, error) {
	o := orm.NewOrm()
	result := []TrendData{}

	// 计算开始时间和结束时间
	now := time.Now()
	endDate := time.Date(now.Year(), now.Month(), now.Day(), 23, 59, 59, 0, now.Location())
	startDate := endDate.AddDate(0, 0, -days)

	// 按日期查询订单数据
	for date := startDate; date.Before(endDate) || date.Equal(endDate); date = date.AddDate(0, 0, 1) {
		dayStart := time.Date(date.Year(), date.Month(), date.Day(), 0, 0, 0, 0, date.Location())
		dayEnd := time.Date(date.Year(), date.Month(), date.Day(), 23, 59, 59, 0, date.Location())

		// 按日期格式化
		dateStr := date.Format("01-02")

		// 构建SQL查询条件
		whereClause := "created_at >= ? AND created_at <= ? AND is_deleted = 0"
		params := []interface{}{dayStart.Unix(), dayEnd.Unix()}

		// 如果是加盟商，添加加盟商过滤条件
		if franchiseId > 0 {
			whereClause += " AND franchise_id = ?"
			params = append(params, franchiseId)
		}

		// 查询当天订单数
		var orderCount int64
		o.Raw("SELECT COUNT(*) FROM ss_order WHERE "+whereClause, params...).QueryRow(&orderCount)

		// 查询当天订单金额
		var orderAmount int64
		o.Raw("SELECT COALESCE(SUM(total_amount), 0) FROM ss_order WHERE "+whereClause, params...).QueryRow(&orderAmount)

		// 添加订单数量数据
		result = append(result, TrendData{
			Date:  dateStr,
			Type:  "订单数",
			Value: orderCount,
		})

		// 添加订单金额数据
		result = append(result, TrendData{
			Date:  dateStr,
			Type:  "收入",
			Value: orderAmount,
		})
	}

	return result, nil
}

// GetSalesAnalysis 获取销售分析数据
func (c *StatisticsController) GetSalesAnalysis() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析时间范围
	startTimeStr := c.GetString("start_time")
	endTimeStr := c.GetString("end_time")

	var startTime, endTime time.Time
	var err error

	if startTimeStr != "" {
		startTime, err = time.Parse("2006-01-02", startTimeStr)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "开始时间格式错误",
			}
			c.ServeJSON()
			return
		}
	} else {
		// 默认过去30天
		startTime = time.Now().AddDate(0, 0, -30)
	}

	if endTimeStr != "" {
		endTime, err = time.Parse("2006-01-02", endTimeStr)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "结束时间格式错误",
			}
			c.ServeJSON()
			return
		}
	} else {
		// 默认今天
		endTime = time.Now()
	}

	// 获取销售趋势数据
	salesTrend, err := getSalesTrend(startTime, endTime, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取销售趋势失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取订单状态分布
	statusDistribution, err := getOrderStatusDistribution(startTime, endTime, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取订单状态分布失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取支付方式分布
	paymentDistribution, err := getPaymentTypeDistribution(startTime, endTime, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取支付方式分布失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"sales_trend":          salesTrend,
			"status_distribution":  statusDistribution,
			"payment_distribution": paymentDistribution,
			"time_range": map[string]string{
				"start_time": startTime.Format("2006-01-02"),
				"end_time":   endTime.Format("2006-01-02"),
			},
		},
	}
	c.ServeJSON()
}

// GetMemberAnalysis 获取会员分析数据
func (c *StatisticsController) GetMemberAnalysis() {
	// 检查权限
	permResult := CheckControllerPermission(c.Ctx)
	if !permResult.Success {
		RespondWithError(&c.Controller, permResult)
		return
	}

	// 解析时间范围
	startTimeStr := c.GetString("start_time")
	endTimeStr := c.GetString("end_time")

	var startTime, endTime time.Time
	var err error

	if startTimeStr != "" {
		startTime, err = time.Parse("2006-01-02", startTimeStr)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "开始时间格式错误",
			}
			c.ServeJSON()
			return
		}
	} else {
		// 默认过去30天
		startTime = time.Now().AddDate(0, 0, -30)
	}

	if endTimeStr != "" {
		endTime, err = time.Parse("2006-01-02", endTimeStr)
		if err != nil {
			c.Data["json"] = map[string]interface{}{
				"success": false,
				"message": "结束时间格式错误",
			}
			c.ServeJSON()
			return
		}
	} else {
		// 默认今天
		endTime = time.Now()
	}

	// 获取会员增长趋势
	memberGrowth, err := getMemberGrowthTrend(startTime, endTime, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员增长趋势失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取会员消费统计
	memberConsumption, err := getMemberConsumptionStats(startTime, endTime, permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员消费统计失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 获取会员等级分布
	memberLevelDistribution, err := getMemberLevelDistribution(permResult.Admin.FranchiseId)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"success": false,
			"message": "获取会员等级分布失败: " + err.Error(),
		}
		c.ServeJSON()
		return
	}

	// 返回结果
	c.Data["json"] = map[string]interface{}{
		"success": true,
		"data": map[string]interface{}{
			"member_growth":      memberGrowth,
			"member_consumption": memberConsumption,
			"level_distribution": memberLevelDistribution,
			"time_range": map[string]string{
				"start_time": startTime.Format("2006-01-02"),
				"end_time":   endTime.Format("2006-01-02"),
			},
		},
	}
	c.ServeJSON()
}

// 获取订单状态分布
func getOrderStatusDistribution(startTime, endTime time.Time, franchiseId int64) ([]models.OrderStatusDistribution, error) {
	filters := make(map[string]interface{})
	filters["start_time"] = startTime.Unix()
	filters["end_time"] = endTime.Unix()

	// 如果是加盟商，需要添加加盟商过滤
	if franchiseId > 0 {
		filters["franchise_id"] = franchiseId
	}

	return models.GetOrderStatusDistribution(filters)
}

// 获取支付方式分布
func getPaymentTypeDistribution(startTime, endTime time.Time, franchiseId int64) ([]models.PaymentTypeDistribution, error) {
	filters := make(map[string]interface{})
	filters["start_time"] = startTime.Unix()
	filters["end_time"] = endTime.Unix()

	// 如果是加盟商，需要添加加盟商过滤
	if franchiseId > 0 {
		filters["franchise_id"] = franchiseId
	}

	return models.GetPaymentTypeDistribution(filters)
}

// 获取销售趋势数据
func getSalesTrend(startTime, endTime time.Time, franchiseId int64) ([]map[string]interface{}, error) {
	o := orm.NewOrm()
	result := []map[string]interface{}{}

	// 计算天数
	days := int(endTime.Sub(startTime).Hours()/24) + 1

	// 构建查询条件
	whereClause := "created_at >= ? AND created_at <= ? AND is_deleted = 0"
	baseParams := []interface{}{startTime.Unix(), endTime.AddDate(0, 0, 1).Unix()}

	// 如果是加盟商，添加加盟商过滤条件
	if franchiseId > 0 {
		whereClause += " AND franchise_id = ?"
		baseParams = append(baseParams, franchiseId)
	}

	// 按日期循环查询
	for i := 0; i < days; i++ {
		currentDate := startTime.AddDate(0, 0, i)
		dayStart := time.Date(currentDate.Year(), currentDate.Month(), currentDate.Day(), 0, 0, 0, 0, currentDate.Location())
		dayEnd := time.Date(currentDate.Year(), currentDate.Month(), currentDate.Day(), 23, 59, 59, 0, currentDate.Location())

		// 日期格式化
		dateStr := dayStart.Format("2006-01-02")

		// 构建当天查询条件
		dayWhereClause := whereClause + " AND created_at >= ? AND created_at <= ?"
		params := append(baseParams, dayStart.Unix(), dayEnd.Unix())

		// 查询当天订单数和金额
		var orderCount int64
		var orderAmount int64
		var successCount int64

		o.Raw("SELECT COUNT(*) FROM ss_order WHERE "+dayWhereClause, params...).QueryRow(&orderCount)
		o.Raw("SELECT COALESCE(SUM(total_amount), 0) FROM ss_order WHERE "+dayWhereClause, params...).QueryRow(&orderAmount)
		o.Raw("SELECT COUNT(*) FROM ss_order WHERE "+dayWhereClause+" AND status = 1", params...).QueryRow(&successCount)

		// 计算成功率
		successRate := 0.0
		if orderCount > 0 {
			successRate = float64(successCount) / float64(orderCount) * 100
		}

		// 添加到结果集
		result = append(result, map[string]interface{}{
			"date":         dateStr,
			"order_count":  orderCount,
			"order_amount": orderAmount,
			"success_rate": successRate,
		})
	}

	return result, nil
}

// 获取会员增长趋势
func getMemberGrowthTrend(startTime, endTime time.Time, franchiseId int64) ([]map[string]interface{}, error) {
	o := orm.NewOrm()
	result := []map[string]interface{}{}

	// 计算天数
	days := int(endTime.Sub(startTime).Hours()/24) + 1

	// 构建查询条件
	whereClause := "created_at >= ? AND created_at <= ? AND is_deleted = 0"
	baseParams := []interface{}{startTime.Unix(), endTime.AddDate(0, 0, 1).Unix()}

	// 如果是加盟商，添加加盟商过滤条件
	if franchiseId > 0 {
		whereClause += " AND franchise_id = ?"
		baseParams = append(baseParams, franchiseId)
	}

	// 按日期循环查询
	for i := 0; i < days; i++ {
		currentDate := startTime.AddDate(0, 0, i)
		dayStart := time.Date(currentDate.Year(), currentDate.Month(), currentDate.Day(), 0, 0, 0, 0, currentDate.Location())
		dayEnd := time.Date(currentDate.Year(), currentDate.Month(), currentDate.Day(), 23, 59, 59, 0, currentDate.Location())

		// 日期格式化
		dateStr := dayStart.Format("2006-01-02")

		// 构建当天查询条件
		dayWhereClause := whereClause + " AND created_at >= ? AND created_at <= ?"
		params := append(baseParams, dayStart.Unix(), dayEnd.Unix())

		// 查询当天新增会员数
		var newMemberCount int64
		o.Raw("SELECT COUNT(*) FROM ss_member WHERE "+dayWhereClause, params...).QueryRow(&newMemberCount)

		// 查询截至当天的累计会员数
		var totalMemberCount int64
		totalParams := []interface{}{dayEnd.Unix()}
		totalWhereClause := "created_at <= ? AND is_deleted = 0"

		if franchiseId > 0 {
			totalWhereClause += " AND franchise_id = ?"
			totalParams = append(totalParams, franchiseId)
		}

		o.Raw("SELECT COUNT(*) FROM ss_member WHERE "+totalWhereClause, totalParams...).QueryRow(&totalMemberCount)

		// 添加到结果集
		result = append(result, map[string]interface{}{
			"date":               dateStr,
			"new_member_count":   newMemberCount,
			"total_member_count": totalMemberCount,
		})
	}

	return result, nil
}

// 获取会员消费统计
func getMemberConsumptionStats(startTime, endTime time.Time, franchiseId int64) (map[string]interface{}, error) {
	o := orm.NewOrm()

	// 构建查询条件
	whereClause := "o.created_at >= ? AND o.created_at <= ? AND o.is_deleted = 0"
	params := []interface{}{startTime.Unix(), endTime.AddDate(0, 0, 1).Unix()}

	// 如果是加盟商，添加加盟商过滤条件
	if franchiseId > 0 {
		whereClause += " AND o.franchise_id = ?"
		params = append(params, franchiseId)
	}

	// 查询消费会员数
	var consumeMemberCount int64
	o.Raw(`
		SELECT COUNT(DISTINCT o.member_id) 
		FROM ss_order o 
		WHERE `+whereClause+` AND o.status = 1
	`, params...).QueryRow(&consumeMemberCount)

	// 查询总会员数
	var totalMemberCount int64
	memberWhereClause := "is_deleted = 0"
	memberParams := []interface{}{}

	if franchiseId > 0 {
		memberWhereClause += " AND franchise_id = ?"
		memberParams = append(memberParams, franchiseId)
	}

	o.Raw("SELECT COUNT(*) FROM ss_member WHERE "+memberWhereClause, memberParams...).QueryRow(&totalMemberCount)

	// 计算消费转化率
	consumeRate := 0.0
	if totalMemberCount > 0 {
		consumeRate = float64(consumeMemberCount) / float64(totalMemberCount) * 100
	}

	// 查询人均消费金额
	var totalAmount int64
	var orderCount int64

	o.Raw(`
		SELECT SUM(total_amount) as total_amount, COUNT(*) as order_count
		FROM ss_order 
		WHERE `+whereClause+` AND status = 1
	`, params...).QueryRow(&totalAmount, &orderCount)

	avgAmount := 0.0
	if consumeMemberCount > 0 {
		avgAmount = float64(totalAmount) / float64(consumeMemberCount)
	}

	// 查询人均订单数
	avgOrderCount := 0.0
	if consumeMemberCount > 0 {
		avgOrderCount = float64(orderCount) / float64(consumeMemberCount)
	}

	return map[string]interface{}{
		"total_member_count":   totalMemberCount,
		"consume_member_count": consumeMemberCount,
		"consume_rate":         consumeRate,
		"total_amount":         totalAmount,
		"avg_amount":           avgAmount,
		"order_count":          orderCount,
		"avg_order_count":      avgOrderCount,
	}, nil
}

// 获取会员等级分布
func getMemberLevelDistribution(franchiseId int64) ([]map[string]interface{}, error) {
	o := orm.NewOrm()
	result := []map[string]interface{}{}

	// 查询所有会员等级
	var levels []*models.MemberLevel
	levelQuery := o.QueryTable(new(models.MemberLevel)).Filter("is_deleted", 0)

	if franchiseId > 0 {
		levelQuery = levelQuery.Filter("franchise_id", franchiseId)
	}

	_, err := levelQuery.All(&levels)
	if err != nil {
		return nil, err
	}

	// 获取会员总数
	var totalCount int64
	memberQuery := o.QueryTable(new(models.Member)).Filter("is_deleted", 0)

	if franchiseId > 0 {
		memberQuery = memberQuery.Filter("franchise_id", franchiseId)
	}

	totalCount, _ = memberQuery.Count()

	// 计算每个等级的会员数量
	for _, level := range levels {
		var levelCount int64
		memberQuery := o.QueryTable(new(models.Member)).Filter("level_id", level.Id).Filter("is_deleted", 0)

		if franchiseId > 0 {
			memberQuery = memberQuery.Filter("franchise_id", franchiseId)
		}

		levelCount, _ = memberQuery.Count()

		// 计算百分比
		percentage := 0.0
		if totalCount > 0 {
			percentage = float64(levelCount) / float64(totalCount) * 100
		}

		result = append(result, map[string]interface{}{
			"level_id":   level.Id,
			"level_name": level.Name,
			"count":      levelCount,
			"percentage": percentage,
		})
	}

	return result, nil
}
